<?php
/**
 * 代码中没有被 catch 到的异常，最后都会被 \App\Exceptions\Handler 捕获到
 * 处理流程：
 * 1、上报异常记录到日志文件里
 * 2、渲染异常响应再发送响应给客户端
 */

namespace App\Exceptions;

use App\Traits\ResponseHelp;
use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Validation\ValidationException;

class Handler extends ExceptionHandler
{
    use ResponseHelp;

    /**
     * A list of the exception types that are not reported.
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     * @param  \Exception $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     * @param  \Illuminate\Http\Request $request
     * @param  \Exception $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        // api或者ajax请求 异常，统一返回json格式
        if ($request->expectsJson() || stripos($request->getRequestUri(), '/api/') !== false) {
            //Validator验证抛出的ValidationException
            if ($exception instanceof ValidationException) {
                return $this->error($exception->errors()->first());
            }

            //找不到模型后抛出的NotFoundHttpException
            if ($exception instanceof ModelNotFoundException) {
                return $this->error('resource not found.');
            }
        }

        return parent::render($request, $exception);
    }

    /**
     * 登录过期后的跳转地址
     * @param \Illuminate\Http\Request $request
     * @param AuthenticationException $exception
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    protected function unauthenticated($request, AuthenticationException $exception)
    {
        return $request->expectsJson()
            ? response()->json(['message' => $exception->getMessage()], 401)
            : redirect()->guest(route('admin.login'));
    }

}
